<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAddUser">新增用户</el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-container">
        <el-input
          v-model="searchForm.username"
          placeholder="请输入用户名"
          style="width: 200px; margin-right: 10px"
        ></el-input>
        <el-select
          v-model="searchForm.status"
          placeholder="请选择状态"
          style="width: 120px; margin-right: 10px"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色"
          width="120"
        ></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditUser(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteUser(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" :prop="isEdit ? '' : 'password'">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
          <div v-if="isEdit" class="el-form-item__help">不修改密码请留空</div>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="userForm.phone"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";

// 表格数据加载状态
const loading = ref(false);

// 搜索表单
const searchForm = reactive({
  username: "",
  status: "",
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = ref("新增用户");
const userFormRef = ref<FormInstance>();

// 用户表单数据
const userForm = reactive({
  id: "",
  username: "",
  password: "",
  email: "",
  phone: "",
  roleId: "",
  status: true,
});

// 表单验证规则
const userRules = ref<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
});

// 用户列表数据
const userList = ref<any[]>([]);

// 角色列表数据
const roleList = ref<any[]>([
  { id: 1, name: "管理员" },
  { id: 2, name: "编辑" },
  { id: 3, name: "普通用户" },
]);

// 获取用户列表
const getUserList = () => {
  loading.value = true;
  // 模拟API请求
  setTimeout(() => {
    // 模拟数据
    const mockData = Array.from({ length: 50 }, (_, index) => ({
      id: index + 1,
      username: `user${index + 1}`,
      email: `user${index + 1}@example.com`,
      phone: `1381234567${index % 10}`,
      roleId: Math.floor(Math.random() * 3) + 1,
      roleName: ["管理员", "编辑", "普通用户"][Math.floor(Math.random() * 3)],
      status: Math.random() > 0.2,
      createTime: new Date(
        Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000
      ).toLocaleString("zh-CN"),
    }));

    // 筛选
    let filteredData = [...mockData];
    if (searchForm.username) {
      filteredData = filteredData.filter((item) =>
        item.username.includes(searchForm.username)
      );
    }
    if (searchForm.status !== "") {
      filteredData = filteredData.filter(
        (item) => item.status === (searchForm.status === "1")
      );
    }

    // 分页
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    userList.value = filteredData.slice(start, end);
    pagination.total = filteredData.length;

    loading.value = false;
  }, 500);
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getUserList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.username = "";
  searchForm.status = "";
  pagination.currentPage = 1;
  getUserList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  getUserList();
};

// 页码变化
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  getUserList();
};

// 新增用户
const handleAddUser = () => {
  isEdit.value = false;
  dialogTitle.value = "新增用户";
  // 重置表单
  Object.assign(userForm, {
    id: "",
    username: "",
    password: "",
    email: "",
    phone: "",
    roleId: "",
    status: true,
  });
  dialogVisible.value = true;
};

// 编辑用户
const handleEditUser = (row: any) => {
  isEdit.value = true;
  dialogTitle.value = "编辑用户";
  // 复制数据到表单
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    password: "", // 编辑时不显示密码
    email: row.email,
    phone: row.phone,
    roleId: row.roleId,
    status: row.status,
  });
  dialogVisible.value = true;
};

// 删除用户
const handleDeleteUser = (id: number) => {
  window.$ElMessageBox
    .confirm("确定要删除勾选的数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      // 模拟删除请求
      loading.value = true;
      setTimeout(() => {
        window.$message.success("删除成功");
        getUserList();
      }, 500);
    });
};

// 状态切换
const handleStatusChange = (row: any) => {
  // 模拟更新状态请求
  setTimeout(() => {
    window.$message.success("状态更新成功");
  }, 300);
};

// 提交表单
const handleSubmit = async () => {
  try {
    await userFormRef.value?.validate();

    // 模拟提交请求
    loading.value = true;
    setTimeout(() => {
      loading.value = false;
      dialogVisible.value = false;
      window.$message.success(isEdit.value ? "编辑成功" : "新增成功");
      getUserList();
    }, 500);
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 组件挂载时获取用户列表
onMounted(() => {
  getUserList();
});
</script>

<style scoped lang="less">
.user-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-container {
    padding: 20px 0;
    display: flex;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>